package com.dreammakerteam.frameworkdemo.test;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

import java.io.IOException;


public class LuceneTest2 {


    public static void main(String[] args) throws Exception {
        // 测试内容
        String[] texts = {"傻子", "java java", "java", "java and lucene is good", "I had study java and jbpm", "I want to study java,hadoop and hbase"};
        // 索引仓库
        Directory  directory = new RAMDirectory();
        // 分词器
        Analyzer analyzer = new SmartChineseAnalyzer();

        // ===========增加索引===========
        // 写配置
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        try {
            // 写流
            IndexWriter iw = new IndexWriter(directory, iwc);
            for (int i = 0; i < texts.length; i++) {
                Document doc = new Document();
                doc.add(new StringField("id", String.valueOf(i), Field.Store.YES));
                doc.add(new TextField("text", texts[i], Field.Store.YES));
                iw.addDocument(doc);
            }
            iw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // ===========查询===========
        try {
            // 读流
            IndexReader ir = DirectoryReader.open(directory);
            // 搜索器
            IndexSearcher searcher = new IndexSearcher(ir);


            // 查询关键字
            Query query = new QueryParser("text", analyzer).parse("傻子");

            TopDocs topDocs = searcher.search(query, 1000);

            // 碰撞结果
            ScoreDoc[] hits = topDocs.scoreDocs;

            for (ScoreDoc hit : hits) {
                Document hitDoc = searcher.doc(hit.doc);
                // 结果按照得分来排序。主要由 关键字的个数和权值来决定
                System.out.println("id:" + hitDoc.get("id") + " text:" + hitDoc.get("text"));
            }
            ir.close();
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }


    }

}
